<!--栏目管理列表-->
<style lang="less">
    @import 'cms_column.less';
</style>

<template>
    <div id="cms_column">
        <Row>
            <Col span="24">
                <Card>
                    <p slot="title" style="height: 32px">
                        <Button type="primary" @click="alertAdd" icon="md-add">新增</Button>
                    </p>
                    <div>
                        <Table :loading="tableLoading" :columns="columnsList" :data="tableData" border
                               disabled-hover></Table>
                    </div>
                </Card>
            </Col>
        </Row>
        <Modal v-model="modalSetting.show" :z-index="399" width="900" :styles="{top: '30px'}" @on-visible-change="doCancel">
            <p slot="header" style="color:#2d8cf0;">
                <Icon type="md-information-circle"></Icon>
                <span>{{formItem.id ? '编辑' : '新增'}}菜单</span>
            </p>
            <Form ref="myForm" :rules="ruleValidate" :model="formItem" :label-width="80">
                <FormItem label="栏目名称" prop="name">
                    <Input v-model="formItem.name" placeholder="请输入栏目名称"></Input>
                </FormItem>
                <FormItem label="ICO图标" prop="icon" class="ico">
                    <Input v-model="formItem.icon" placeholder="请直接粘贴ICO图标代码"></Input>
                    <Button type="dashed" style="color: #DF8600;width: 200px" @click="showIco">选择ICO图标</Button>
                </FormItem>
                <FormItem label="栏目关键字" prop="keywords">
                    <Input v-model="formItem.keywords" type="textarea" :rows="1"
                           placeholder="请输入关键字 多个用英文逗号“，”隔开"></Input>
                </FormItem>
                <FormItem label="缩略图" prop="menuimg" class="imgUpload">
                    <div class="demo-upload-list" v-if="formItem.menuimg">
                        <img :src=" imgSrc + formItem.menuimg" style="max-height: 150px" @click="imgPreview">
                        <div class="demo-upload-list-cover">
                            <Icon type="ios-trash-outline" @click.native="handleImgRemove()"></Icon>
                        </div>
                    </div>
                    <input v-if="formItem.menuimg" v-model="formItem.menuimg" type="hidden" name="image">
                    <Upload type="drag"
                            :action="uploadUrl"
                            :headers="uploadHeader"
                            v-if="!formItem.menuimg"
                            :format="['jpg','jpeg','png']"
                            :max-size="5120"
                            :data="{
                                userid: formItem.userid,
                                username: formItem.username,
                                ismenuimg: 1
                              }"
                            :on-success="handleImgSuccess"
                            :on-format-error="handleImgFormatError"
                            :on-exceeded-size="handleImgMaxSize"
                            style="display: inline-block;width:200px;">
                        <div style="width: 200px;height:90px;color: #2aa955;padding-top: 10px;">
                            <Icon type="ios-cloud-upload" size="28"></Icon>
                            <p>支持拖拽上传 jpg jpeg png</p>
                        </div>
                    </Upload>
                    <Button type="dashed" style="color: #DF8600;width: 200px" @click="showFilestList">图片空间列表</Button>
                </FormItem>
                <FormItem label="栏目简介" prop="info">
                    <Input v-model="formItem.info" type="textarea" :rows="3" placeholder="请输入栏目简介"></Input>
                </FormItem>
                <FormItem label="父级菜单" prop="fid">
                    <Select v-model="formItem.fid" filterable>
                        <Option :value="0">顶级菜单</Option>
                        <Option v-for="(item,index) in tableData" :value="item.id" :key="index">{{ item.showName }}
                        </Option>
                    </Select>
                </FormItem>
                <FormItem label="终极栏目" prop="islast">
                    <RadioGroup v-model="status" @on-change="statusType">
                        <Radio label="是"></Radio>
                        <Radio label="否"></Radio>
                    </RadioGroup>
                    <span style="color: #FD6732">只有终极栏目才可以增加内容</span>
                </FormItem>
                <FormItem label="菜单排序" prop="sort">
                    <InputNumber :min="0" v-model="formItem.sort"></InputNumber>
                    <Tag color="error" style="margin-left:5px">数字越小越靠前</Tag>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" @click="cancel" style="margin-right: 8px">取消</Button>
                <Button type="primary" @click="submit" :loading="modalSetting.loading">确定</Button>
            </div>
        </Modal>

        <!--图片预览model-->
        <Modal v-model="imgModel" :footer-hide="true" class-name="imgPreview">
            <p slot="header" style="text-align: left">
                <span>图片预览</span>
            </p>
            <div style="text-align: center">
                <img :src="modelImg" width="100%">
            </div>
        </Modal>
        <!--图片空间列表model-->
        <filestList ref="filestList" @childImgUrl="childImgUrl"></filestList>
    </div>
</template>

<script>
    import {CmsColumnIndex, CmsColumnAdd, CmsColumnEdit, CmsColumnDel, CmsColumnChangeStatus} from '@/api/cms/menu'
    import filestList from '@/components/cms/cms_fileslist'
    let userInfo
    const editButton = (vm, h, currentRow, index) => {
        return h('Button', {
            props: {
                type: 'primary'
            },
            style: {
                margin: '0 5px'
            },
            on: {
                'click': () => {
                    vm.formItem = JSON.parse(JSON.stringify(currentRow))
                    vm.formItem.username = userInfo.username
                    vm.formItem.userid = userInfo.id

                    vm.formItem.menuimgidBefore = currentRow.menuimgid
                    vm.modalSetting.show = true
                    vm.modalSetting.index = index
                    // vm.formItem.islast = currentRow.islast
                    if (currentRow.islast === 1)
                        vm.status = '是'
                    else
                        vm.status = '否'
                }
            }
        }, '编辑')
    }
    const deleteButton = (vm, h, currentRow, index) => {
        return h('Poptip', {
            props: {
                confirm: true,
                title: '您确定要删除这条数据吗? ',
                transfer: true
            },
            on: {
                'on-ok': () => {
                    CmsColumnDel({'id': currentRow.id}).then(function (response) {
                        currentRow.loading = false
                        if (response.data.code === 1) {
                            vm.tableData.splice(index, 1)
                            vm.$Message.success(response.data.msg)
                        } else {
                            vm.$Message.error(response.data.msg)
                        }
                    })
                }
            }
        }, [
            h('Button', {
                style: {
                    margin: '0 5px'
                },
                props: {
                    type: 'error',
                    placement: 'top',
                    loading: currentRow.isDeleting
                }
            }, '删除')
        ])
    }
    export default {
        name: 'cms_column',
        data() {
            userInfo = JSON.parse(sessionStorage.getItem('userData'))
            return {
                imgSrc: '', // 图片显示地址
                uploadUrl: '', // 图片上传接口地址
                uploadHeader: {},
                status: '否',
                columnsList: [
                    {
                        title: '栏目ID',
                        key: 'id',
                        width: 75,
                        align: 'center'
                    },
                    {
                        title: '栏目名称',
                        align: 'left',
                        key: 'showName',
                        width: 150
                    },
                    {
                        title: '栏目简介',
                        align: 'left',
                        key: 'info'
                    },
                    {
                        title: '排序',
                        align: 'center',
                        key: 'sort',
                        width: 80
                    },
                    {
                        title: '是否终极栏目',
                        align: 'center',
                        width: 120,
                        key: 'islast',
                        render: (h, params) => {
                            if (params.row.islast === 1)
                                return h('div', [
                                    h('span', {
                                        style: {
                                            color: '#FD6732'
                                        }
                                    }, '是')
                                ])
                            else
                                return h('div', [
                                    h('span', '否')
                                ])
                        }
                    },
                    {
                        title: '状态',
                        align: 'center',
                        key: 'hide',
                        width: 100
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'handle',
                        width: 200,
                        handle: ['edit', 'delete']
                    }
                ],
                tableLoading: false,
                tableData: [],
                modalSetting: {
                    show: false,
                    loading: false,
                    index: 0
                },
                formItem: {
                    name: '',
                    menuimg: '',
                    menuimgid: '', // 标题缩略图ID
                    menuimgidBefore: '', // 编辑之前的缩略图Id 用于后台判断是否修改缩略图
                    icon: '', // 栏目图标
                    info: '',
                    keywords: '', // 关键字
                    fid: 0,
                    islast: 0,
                    sort: 0,
                    id: 0,
                    userid: '', // 用户id
                    username: '' // 用户名称
                },
                ruleValidate: {
                    name: [
                        {required: true, message: '菜单名称不能为空', trigger: 'blur'}
                    ]
                },
                imgModel: false, // 图片预览model
                modelImg: '', // 图片src
            }
        },
        created() {
            this.imgSrc = this.$imgSrc
            this.init()
            this.getList()
        },
        components: {
            filestList
        },
        methods: {
            init() {
                let vm = this
                // 文件上传地址
                vm.uploadUrl = this.$baseUrl + 'CmsColumn/upload'
                vm.uploadHeader = {'ApiAuth': userInfo.apiAuth}
                this.columnsList.forEach(item => {
                    if (item.handle) {
                        item.render = (h, param) => {
                            let currentRowData = vm.tableData[param.index]
                            return h('div', [
                                editButton(vm, h, currentRowData, param.index),
                                deleteButton(vm, h, currentRowData, param.index)
                            ])
                        }
                    }
                    if (item.key === 'hide') {
                        item.render = (h, param) => {
                            let currentRowData = vm.tableData[param.index]
                            return h('i-switch', {
                                attrs: {
                                    size: 'large'
                                },
                                props: {
                                    'true-value': 0,
                                    'false-value': 1,
                                    value: currentRowData.hide
                                },
                                on: {
                                    'on-change': function (status) {
                                        CmsColumnChangeStatus({
                                            status: status,
                                            id: currentRowData.id
                                        }).then(function (response) {
                                            let res = response.data
                                            if (res.code === 1) {
                                                vm.$Message.success(res.msg)
                                            } else {
                                                vm.$Message.error(res.msg)
                                                vm.getList()
                                            }
                                            vm.cancel()
                                        })
                                    }
                                }
                            }, [
                                h('span', {
                                    slot: 'open'
                                }, '显示'),
                                h('span', {
                                    slot: 'close'
                                }, '隐藏')
                            ])
                        }
                    }
                })
            },
            alertAdd() {
                this.formItem = {}
                // this.$refs['myForm'].resetFields()
                this.formItem.id = 0
                this.init()
                this.modalSetting.show = true
            },
            statusType(e) {
                switch (e) {
                    case '是':
                        this.formItem.islast = 1
                        break
                    default:
                        this.formItem.islast = 0
                }
            },
            submit() {
                let self = this
                this.$refs['myForm'].validate((valid) => {
                    if (valid) {
                        // self.modalSetting.loading = true;
                        if (this.formItem.id === 0) {
                            CmsColumnAdd(this.formItem).then(response => {
                                if (response.data.code === 1) {
                                    self.$Message.success(response.data.msg)
                                    self.getList()
                                    self.cancel()
                                } else {
                                    self.$Message.error(response.data.msg)
                                }
                            }).catch(err => {
                                console.log(err)
                            })
                        } else {
                            CmsColumnEdit(this.formItem).then(response => {
                                if (response.data.code === 1) {
                                    self.$Message.success(response.data.msg)
                                    self.getList()
                                    self.cancel()
                                } else {
                                    self.$Message.error(response.data.msg)
                                }
                            })
                        }
                    }
                })
            },
            cancel() {
                this.modalSetting.show = false
            },
            doCancel(data) {
                if (!data) {
                    this.modalSetting.loading = false
                    this.modalSetting.index = 0
                }
            },
            getList() {
                let vm = this
                vm.tableLoading = true
                CmsColumnIndex().then(response => {
                    let res = response.data
                    vm.tableLoading = false
                    if (res.code === 1) {
                        vm.tableData = res.data.list
                    } else {
                        vm.$Message.error(res.msg)
                    }
                })
            },
            // 上传部分
            handleImgFormatError(file) {
                this.$Notice.warning({
                    title: '文件类型不合法',
                    desc: file.name + '的文件类型不正确，请上传jpg或者png图片。'
                })
            },
            handleImgRemove() {
                this.formItem.menuimg = ''
            },
            handleImgSuccess(response) {
                if (response.code === 1) {
                    this.$Message.success(response.msg)
                    this.$set(this.formItem, 'menuimg', response.data.fileUrl)
                    // this.formItem.menuimg = response.data.fileUrl
                    this.formItem.menuimgid = response.data.fileId
                } else {
                    this.$Message.error(response.msg)
                }
            },
            handleImgMaxSize(file) {
                this.$Notice.warning({
                    title: '文件大小不合法',
                    desc: file.name + '太大啦! 请上传小于5M的文件。'
                })
            },
            // 显示图片空间列表
            showFilestList() {
                this.$refs.filestList.showFilestList('menu')
            },
            // 获取子组件图片空间列表传来的imgUrl
            childImgUrl(imgData) {
                // console.log(imgData);
                this.$set(this.formItem, 'menuimg', imgData.url)
                this.formItem.menuimgid = imgData.id
            },
            // 图片预览
            imgPreview(e) {
                this.modelImg = e.target.src
                this.imgModel = true
            },
            // 选择ICO图标
            showIco() {
                window.open('https://www.iviewui.com/components/icon#SYTB')
            },
        }
    }
</script>
